package com.bxx.service.impl;

import com.bxx.dao.*;
import com.bxx.pojo.*;
import com.bxx.service.MyExamService;
import com.bxx.util.PageUtil;
import com.bxx.util.R;
import com.bxx.vo.TestPaperQuestionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class MyExamServiceImpl implements MyExamService {

    //注入用户持久层
    @Autowired
    private UserDao userDao;
    //注入考试班级持久层
    @Autowired
    private ExamClassDao examClassDao;
    //注入考试持久层
    @Autowired
    private ExamDao examDao;
    //注入试卷题库持久层
    @Autowired
    private TestPaperQuestionDao testPaperQuestionDao;
    //注入题目持久层
    @Autowired
    private QuestionDao questionDao;

    //注入学生考试答案持久层
    @Autowired
    private StudentExamAnswerDao studentExamAnswerDao;
    //学生考试持久层
    @Autowired
    private StudentExamDao studentExamDao;
    //成绩持久层
    @Autowired ScoreDao scoreDao;

    @Override
    public PageUtil<Exam> getExamsByUserId(String userId) {
        PageUtil<Exam> pageUtil = new PageUtil<Exam>();
        //获取用户所在的班级id
        String classId = userDao.getClassIdByUserId(userId);
        if (classId == null || "".equals(classId))  return pageUtil;

        //根据班级id获取相关考试id集合
        List<String> examIdList = examClassDao.getExamIdsByClassId(classId);

        System.out.println("examIdList>" + examIdList.toString());

        if(examIdList == null) return pageUtil;
        List<Exam> exams = examDao.getExamsByExamIdList(examIdList);
        Integer examsCount = examDao.getExamsCountByExamIdList(examIdList);

        pageUtil.setCode(0);
        pageUtil.setData(exams);
        pageUtil.setCount(examsCount);

        return pageUtil;
    }

    @Override
    public R startExam(String examId, String userId) {
        //根据考试id获取考试信息
        Exam exam = examDao.getExamByExamId(examId);
        if(exam == null) return R.error("考试信息获取失败");

        //查询该学生是否已经参加过考试
        StudentExam studentExam = new StudentExam();
        studentExam.setExamId(examId);
        studentExam.setStudentId(userId);
        StudentExam studentExamRes = studentExamDao.getStudentExamByStudentIdAndExamId(studentExam);

        //如果已经参加过考试
        if(studentExamRes != null) return R.error("你已完成，无法再次进入考试！");

        if (exam.getExamStatus() != 1 || exam.getExamStartTime().after(new Date()))
            return R.error("考试还未开始！");

        return R.ok(exam);
    }

    @Override
    public R getTestQuestions(String examId) {
        //根据考试id获取考试信息
        Exam exam = examDao.getExamByExamId(examId);
        if (exam == null) return R.error("考试数据获取失败！");
        //根据试卷id获取所有题目id
        List<String> questionIds = testPaperQuestionDao.getQuestionIdsByTestPaperId(exam.getTestPaperId());

        if(questionIds == null) return R.error("试卷题库数据获取失败！");
        //根据题目id集合获取所有题目
        List<Question> questions = questionDao.getQuestionsByQuestionIdList(questionIds);
        if (questions == null) return R.error("题目数据获取失败！");

        //格式化该试卷题库
        List<TestPaperQuestionVO> testPaperQuestionVOs = this.formatQuestions(questions);

        return R.ok(testPaperQuestionVOs);
    }

    @Override
    public List<TestPaperQuestionVO> formatQuestions(List<Question> questions) {
        List<String> questionTypeIdList = new ArrayList<String>();
        List<TestPaperQuestionVO> testPaperQuestionVOs = new ArrayList<TestPaperQuestionVO>();
        for (Question question: questions) {
            if (!questionTypeIdList.contains(question.getQuestionTypeId())){
                QuestionType questionType = question.getQuestionType();
                questionTypeIdList.add(questionType.getQuestionTypeId());
                TestPaperQuestionVO testPaperQuestionVO = new TestPaperQuestionVO();
                testPaperQuestionVO.setQuestionTypeId(questionType.getQuestionTypeId());
                testPaperQuestionVO.setQuestionTypeName(questionType.getQuestionTypeName());
                testPaperQuestionVOs.add(testPaperQuestionVO);
            }
        }

        for (TestPaperQuestionVO vo:testPaperQuestionVOs) {
            for (Question question: questions) {
                //判断是否是同一类型的题目
                if (question.getQuestionTypeId().equals(vo.getQuestionTypeId())){
                    if (vo.getQuestions() == null){
                        vo.setQuestions(new ArrayList<Question>());
                    }
                    vo.getQuestions().add(question);
                }
            }
        }

        return testPaperQuestionVOs;
    }

    @Override
    public R submitExam(ExamDTO examDTO) {
        if (examDTO == null) return R.error("考试提交失败，本次考试数据获取异常！");
        String studentId = examDTO.getUserId();
        if (studentId == null || "".equals(studentId)) return R.error("身份信息验证失败！");
        String examId = examDTO.getExamId();
        //获取考试信息
        Exam exam = examDao.getExamByExamId(examId);

        //新建试卷题库对象
        TestPaperQuestion testPaperQuestion = new TestPaperQuestion();
        testPaperQuestion.setTestPaperId(exam.getTestPaperId());

        //添加学生考试提交的答案
        AnswerDTO[] answerDTOs = examDTO.getAnswerDTOs();
        int res = 0;
        for (int i = 0; i < answerDTOs.length; i++) {

            //根据考试试卷id和题库id获取试卷题库id集合
            testPaperQuestion.setQuestionId(answerDTOs[i].getId());
            String testPaperQuestionId = testPaperQuestionDao.getTestPaperQuestionIdByTestPaperIdAndQuestionId(testPaperQuestion);
            if(testPaperQuestionId != null){
                //创建学生考试答案
                StudentExamAnswer studentExamAnswer = new StudentExamAnswer();
                studentExamAnswer.setStudentExamAnswerId(UUID.randomUUID().toString());
                studentExamAnswer.setStudentId(studentId);
                studentExamAnswer.setAnswer(answerDTOs[i].getValue());
                studentExamAnswer.setScore(0.0);
                studentExamAnswer.setTestPaperQuestionId(testPaperQuestionId);
                //添加学生考试答案
                Integer r = studentExamAnswerDao.insertStudentExamAnswer(studentExamAnswer);
                if (r > 0){
                    res ++;
                }
            }

        }
        if (res < 1) return R.error("考试提交失败！");
        //创建学生考试对象
        StudentExam studentExam = new StudentExam();
        studentExam.setStudentId(studentId);
        studentExam.setExamId(examDTO.getExamId());
        //设置默认未批改:批阅状态（0、未批改；1、已批改）
        studentExam.setStatus(0);
        //添加学生考试
        studentExamDao.insertStudentExam(studentExam);

        //创建成绩对象
        Score score = new Score();
        score.setScoreId(UUID.randomUUID().toString());
        score.setScore(0.0);
        //设置默认考试正常:状态（0、正常；1、缺考；2、作弊）
        score.setScoreStatus(0);
        score.setTestPaperId(exam.getTestPaperId());
        score.setStudentId(studentId);
        //添加初始成绩
        scoreDao.insertScore(score);
        return R.ok("考试提交成功！");
    }
}
